<?php

	class jso extends obj{
		
		function to_array(){
			return get_object_vars($this);
		}
		
		function to_numeric(){
			$a = array();
			foreach($this->to_array() as $v) $a[] = $v;
			return $a;
		}
		
		function length(){
			return count($this->to_array());
		}
		
		function index(){
			return array_keys($this->to_array());
		}
		
		function first(){
			return array_shift($this->to_array());
		}
		
		function last(){
			return array_pop($this->to_array());	
		}
		
		function firstkey(){
			return key($this->to_array());	
		}
		
		function lastkey(){
			$a = $this->to_array();
			end($a);
			return key($a);	
		}
		
		function remove($k){
			unset($this->$k);	
		}
		
		function clear(){
			foreach($this->index() as $k) unset($this->$k);
		}
		
		function get_clear(){
			$a = $this->to_array();
			$this->clear();
			return $a;
		}
		
		function rsort(){
			$this->sort('r');
		}
		
		function ksort(){
			$this->sort('k');
		}
		
		function krsort(){
			$this->sort('kr');
		}
		
		function sort($f=false){
			$a = $this->get_clear();
			switch($f){
				case 'r': 	arsort($a); 	break;
				case 'k': 	ksort($a); 		break;
				case 'kr': 	krsort($a); 	break;
				default: 	asort($a); 		break;
			}
			$this->set($a);
		}
		
		function insert_before($e, $o, $v=NULL){
			if(is_scalar($o)) return $this->insert_before($e, array($o, $v));
			if(!isset($this->$e)) return $this->set($o);
			foreach($this->get_clear() as $k=>$v){
				if($k == $e) $this->set($o);
				$this->$k = $v;
			}
		}
		
		function sub_isset($k, $sk){ 
			return (!isset($this->$k)) ? false : is_object($v = $this->$k) ? isset($v->$sk) : is_array($v) ? isset($v[$sk]) : false;	
		}
		
		function sub_get($k, $sk){
			return (!$this->sub_isset($k, $sk)) ? NULL : is_object($this->$k) ? $this->$k->$sk : $this->$k[$sk];
		}
	
		function order_by_subkey($sk, $r=false){
			$a = array();
			foreach($this->index() as $k) $a[$k] = $this->sub_get($k, $sk);
			if(!$r) asort($a); 
			else arsort($a);
			$this->set_order(array_keys($a));
		}
		
		function set_order($order){
			$a = $this->get_clear();
			foreach($order as $k){
				if(!isset($a[$k])) continue;
				$this->$k = $a[$k];
				unset($a[$k]);
			}
			$this->set($a);
		}		
	}

